package jsyf.oa.service.system;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.system.MilkDao;
import jsyf.oa.entity.system.MilkEntity;
import jsyf.oa.facade.system.MilkFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by Administrator on 2018/11/8 0008.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class MilkService implements MilkFacade {
    @Autowired
    private MilkDao milkDao;

    @Override
    public String save(String jsonData) {
        MilkEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), MilkEntity.class);
        Integer rows = null;
        if ("0".equals(entity.getId()) || StringUtils.isBlank(entity.getId())) {
            rows = milkDao.add(entity);
        }
        return rows == 0 ? "" : entity.getId();
    }

    @Override
    public String update(String jsonData) {
        JSONObject jsonParam = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String information = jsonParam.getString("information");
        Integer buyFlag = jsonParam.getInteger("buyFlag");
        Integer rows;
        MilkEntity model = (MilkEntity) milkDao.getIBaseEntityByInformation(information);
        model.setBuyFlag(buyFlag);
        rows = milkDao.update(model);
        return rows == 0 ? "" : model.getId();
    }
    @Override
    public JSONObject getByInformation(String jsonData) {
        JSONObject jsonParam = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String information = jsonParam.getString("information");
        List<JSONObject> jsonObject =milkDao.getJSONListByCondition(" AND INFORMATION = ?", new Object[]{information});
        if (jsonObject != null && jsonObject.size() > 0) {
            return jsonObject.get(0);
        } else {
            return null;
        }
    }

    @Override
    public List<JSONObject> getByCondition() {
        return milkDao.getJSONListByCondition("",new Object[]{});
    }

    @Override
    public JSONObject getWxId(String jsonData) {
        JSONObject jsonParam = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        JSONObject objResult = new JSONObject();
        JSONObject milk = milkDao.isWxId(jsonParam.getString("wxId"));
        Integer flag = milk.getInteger("count");
        if (flag > 0) {
            objResult.put("success", "true");
            objResult.put("information", milk.getString("information"));
            objResult.put("buyFlag", milk.getString("buyFlag"));
        } else {
            objResult.put("success", "false");
        }
        return objResult;
    }
}
